package com.kyd.push.mqservice;

import com.alibaba.fastjson.JSON;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.Consumer;
import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import com.kyd.push.model.Order;
import com.kyd.push.model.OrderMqContext;
import com.kyd.push.model.PushLog;
import com.kyd.push.model.PushTypeEnum;
import com.kyd.push.model.repository.PushLogRepository;
import com.kyd.push.mq.vo.OrderPushVO;
import com.kyd.push.push.JPushKit;
import com.kyd.push.push.PushRequest;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Optional;
import java.util.Properties;

/**
 * ConsumerTest
 *
 * @author kejw on 2018/9/27
 */
public class ConsumerOrder {

	@Autowired
	private PushLogRepository pushLogRepository;

	public  void consumer() {

		Properties properties = new Properties();
		properties.put(PropertyKeyConst.ConsumerId, "CID_kyd_consignor");
		properties.put(PropertyKeyConst.AccessKey, "LTAIASBYEVqRq4Wb");
		properties.put(PropertyKeyConst.SecretKey, "x0x85HMvoxVYjHXuBNlkafD2ElnrGB");
		properties.put(PropertyKeyConst.ONSAddr, "http://onsaddr-internet.aliyun.com/rocketmq/nsaddr4client-internet");

		Consumer consumer = ONSFactory.createConsumer(properties);
		consumer.subscribe("kyd_order", "*", (message, context) -> {

			try {
				String body = new String(message.getBody());
				OrderMqContext mqContext = JSON.parseObject(body, OrderMqContext.class);
				Order o = mqContext.getOrder();
				Long pushId = mqContext.getPushId();

				Optional<PushLog> optional = pushLogRepository.findById(pushId);
				PushLog pushLog = optional.get();


				OrderPushVO orderPushVO = new OrderPushVO();
				orderPushVO.setOrderId(o.getId());

				PushRequest request = PushRequest.newInstance().setNotification("你有新运单").addExtra(PushTypeEnum.ORDER, orderPushVO).addExtra("voiceMsg","哈哈哈" );

				JPushKit.sendPushByAlias(request, "");
				// 添加消息记录

				return Action.CommitMessage;
			} catch (Exception e) {
				//消费失败
				return Action.CommitMessage;
			}
		});

		consumer.start();
	}

}
